package com.org.msmvc.sys.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.org.util.HttpUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import com.org.msmvc.sys.entity.Roles;
import com.org.msmvc.sys.entity.SysUser;
import com.org.msmvc.sys.service.LogService;
import com.org.msmvc.sys.service.RolesService;
import com.org.msmvc.sys.service.SystemControllerLog;
import com.org.msmvc.sys.service.UserService;
import com.org.util.CommUtil;
import com.org.util.excel.ExcelUtil;

/**
 * 用户管理
 * @author  zsh
 */
@Controller
@RequestMapping("sysUser")
public class UserController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private RolesService rolesService;
	@Autowired
	private LogService logService;
	@RequestMapping(value = "/query/{operate}")
	public ModelAndView execute(@PathVariable("operate") String operate,HttpServletRequest request,
			HttpServletResponse response) throws NumberFormatException, Exception {
		ModelAndView model = new ModelAndView();
		if (operate.equals("tolist")) {//列表显示
			model.setViewName("/user/listUser");
		} else if (operate.equals("add")) {//新增页面
			
			model.setViewName("/user/addUser");
		}else if (operate.equals("edit")) {//修改页面
			String id=request.getParameter("id");
			SysUser usr=userService.getUserById(Integer.valueOf(id));
			model.addObject("user", usr);
			model.setViewName("/user/editUser");
		}else if(operate.equals("show")){//查看详细
			String id=request.getParameter("id");
			SysUser usr=userService.getUserById(Integer.valueOf(id));
			model.addObject("user", usr);
			model.setViewName("/user/showUser");
		}else if(operate.equals("userAuthority")){//查看详细
			String userName=request.getParameter("userName");
			List<String> userRole=rolesService.getUserRole(userName);
			String u="";
			if(userRole.size()>0){
				for(String ur:userRole){
					u+=ur+",";
				}
			}
			model.addObject("userName", userName);
			model.addObject("uRole",u);
			model.setViewName("/user/userRoleAuthority");
		}else if(operate.equals("toLogsList")){//操作日志
			model.setViewName("/user/logsList");
		}else if(operate.equals("toUpdatePass")){//密码修改
			HttpSession session = request.getSession();    
	        //读取session中的用户    
	        String currentUser = (String)session.getAttribute("currentUser");    
			model.addObject("username", currentUser);
			model.setViewName("/user/updatePass");
		}else if(operate.equals("toUpUserImg")){//密码修改
			model.addObject("userIDS", request.getParameter("userIDS"));
			model.setViewName("/user/upUserImg");
		}
		return model;
	}

	@RequestMapping("/list")
	@ResponseBody
	public Map<String, Object> listJson(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		/**
		 * 想要在页面展现数据,必须返回ModelAndView类型,返回String是不能获取数据的
		 */
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, String[]> getParams = request.getParameterMap(); // 获取查询条件信息
		String values = "";
		for (String key : getParams.keySet()) {
			values = Arrays.toString(getParams.get(key));
			params.put(key, values.substring(1, values.lastIndexOf("]")));
		}

		long totalCount = userService.getCounts(params); // 获取记录总数
		// 每页显示的记录数     
		String pageSize = request.getParameter("pagesize");
		// 当前页
		String page = request.getParameter("page");
		//($page-1)*$pagesize
		int startIndex=(Integer.valueOf(page)-1)*Integer.valueOf(pageSize);
		params.put("startIndex", startIndex);
		params.put("pageSize", Integer.valueOf(pageSize));
		List<SysUser> users = userService.getPageList(params);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", users);
		map.put("Total", totalCount);
		return map;
	}
	@SystemControllerLog(description = "新增用户")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveUser(@ModelAttribute("users") SysUser users,HttpServletRequest request,
										HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag=false;
		String message="";
		int i = 0;
		i = userService.insert(users);
		//从后台代码获取国际化信息
		RequestContext requestContext = new RequestContext(request);
		if(i>0){
			flag=true;
			message=requestContext.getMessage("user_add_success");
		}else{
			message=requestContext.getMessage("user_add_false");
		}
		map.put("message",message);
		map.put("flag",flag);
		return map;
	}
	@SystemControllerLog(description = "更新用户")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateUser(@ModelAttribute("users") SysUser users,HttpServletRequest request,
										  HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag=false;
		String message="";
		int i = 0;
		i = userService.updateUser(users);
		//从后台代码获取国际化信息
		RequestContext requestContext = new RequestContext(request);
		if(i>0){
			flag=true;
			message=requestContext.getMessage("user_update_success");
		}else{
			message=requestContext.getMessage("user_update_false");
		}
		map.put("message",message);
		map.put("flag",flag);
		return map;
	}
	/*@SystemControllerLog(description = "删除用户")*/
	@RequestMapping(value = "/userDel", method = RequestMethod.POST)
	@ResponseBody
	public Map delUser(@RequestParam("id") String id,HttpServletRequest request,
					   HttpServletResponse response ) throws NumberFormatException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		int i = 0;
		i = userService.deleteByPrimaryKey(Integer.valueOf(id));
		//从后台代码获取国际化信息
		RequestContext requestContext = new RequestContext(request);
		if(i>=0){
			map.put("message",requestContext.getMessage("user_del_success"));
		}else{
			map.put("message",requestContext.getMessage("user_del_false"));
		}
		return map;
	}
	
	/**
	 * 重置用户密码
	 * @param id
	 * @return
	 * @throws NumberFormatException
	 * @throws Exception
	 */
	@SystemControllerLog(description = "重置用户密码")
	@RequestMapping(value = "/restPassword", method = RequestMethod.POST)
	@ResponseBody
	public Map restPassword(@RequestParam("id") String id ,HttpServletRequest request,
							HttpServletResponse response) throws NumberFormatException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		
		int i = 0;
		i = userService.restPassword(id,request.getParameter("userName"));
		//从后台代码获取国际化信息
		RequestContext requestContext = new RequestContext(request);
		if(i>=0){
			map.put("message",requestContext.getMessage("user_password_reset_success"));
		}else{
			map.put("message",requestContext.getMessage("user_password_reset_false"));
		}
		return map;
	}
	/**
	 * 修改密码
	 * @param
	 * @return
	 * @throws Exception
	 */
	@SystemControllerLog(description = "修改用户密码")
	@RequestMapping(value = "/updatePass", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updatePass(HttpServletRequest req, HttpServletResponse res) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String[]> getParams = req.getParameterMap(); // 获取参数信息
		Map<String, Object> params = new HashMap<String, Object>();
		String values = "";
		for (String key : getParams.keySet()) {
			values = Arrays.toString(getParams.get(key));
			params.put(key, values.substring(1, values.lastIndexOf("]")));
		}
		boolean flag=false;
		String message="";
		int i = 0;
		i = userService.updatePassword(params);
		//从后台代码获取国际化信息
		RequestContext requestContext = new RequestContext(req);
		if(i>0){
			flag=true;
			message=requestContext.getMessage("user_password_update_success");
		}else{
			message=requestContext.getMessage("user_password_update_false");
		}
		map.put("message",message);
		map.put("flag",flag);
		return map;
	}
	
	/**
	 * 操作日志
	 * 
	 * @param req
	 * @param res
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/logsList")
	@ResponseBody
	public Map<String, Object> logsList(HttpServletRequest req, HttpServletResponse res)
			throws UnsupportedEncodingException {
		Map<String, Object> params = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, String[]> getParams = req.getParameterMap(); // 获取查询条件信息
		String values = "";
		for (String key : getParams.keySet()) {
			values = Arrays.toString(getParams.get(key));
			params.put(key, values.substring(1, values.lastIndexOf("]")));
		}
		// 每页显示的记录数
		String pageSize = req.getParameter("pagesize");
		// 当前页
		String page = req.getParameter("page");
		// ($page-1)*$pagesize
		int startIndex = (Integer.valueOf(page) - 1) * Integer.valueOf(pageSize);
		params.put("startIndex", startIndex);
		params.put("pageSize", Integer.valueOf(pageSize));
		
		long totalCount = logService.logsCount(params); // 获取记录总数
		list = logService.logsList(params);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", list);
		map.put("Total", totalCount);

		return map;
	}
	
	/**
	 * 上传用户头像
	 * @param req
	 * @param res
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/upCImg")
	@ResponseBody
	public Map<String, Object>   upCImg(HttpServletRequest req,HttpServletResponse res) throws UnsupportedEncodingException{
		Map<String, Object> params = new HashMap<String, Object>();
	
		Map<String, String[]> getParams = req.getParameterMap(); // 获取查询条件信息
		String values = "";
		for (String key : getParams.keySet()) {
			values = Arrays.toString(getParams.get(key));
			params.put(key, values.substring(1, values.lastIndexOf("]")));

		}
		boolean flag=false;
		String message="";
		int i=userService.upUserImg(params);
		//从后台代码获取国际化信息
		RequestContext requestContext = new RequestContext(req);
		if(i>0){
			flag=true;
			message=requestContext.getMessage("user_img_up_success");
		}else{
			flag=false;
			message=requestContext.getMessage("user_img_up_false");
		}
		params.put("message",message);
		params.put("flag",flag);
		return params;
	}


	private void getIP(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
	}

}
